package cn.leonis.leetcode;

import java.util.Arrays;

/**
 * @Author Tobi
 * @Date 2021-12-10 下午4:53
 * 反转字符串3
 * leetcode557
 */
public class ReverseString3Solution {

    public static void main(String[] args) {

    }

    /**
     * 解法：使用额外的空间存储
     * @param s
     * @return
     */
    public String reverseWords(String s) {
        StringBuffer sb = new StringBuffer();
        int length = s.length();
        String[] s1 = s.split(" ");
        for (String s2: s1) {
            int len = s2.length();
            char[] chars = s2.toCharArray();
            reverseString(chars);
            sb.append(chars);
            sb.append(" ");
        }

        return sb.toString().substring(0, length);
    }

    /**
     * 解法：双指针
     * @param s
     */
    public void reverseString(char[] s) {
        int left = 0, right = s.length - 1;
        while (left < right) {
            if (s[left] != s[right]) {
                char c = s[left];
                s[left] = s[right];
                s[right] = c;
            }
            ++left;
            --right;
        }
    }
}
